package com.socool.sinofaith.service;

import java.util.ArrayList;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import com.socool.sinofaith.R;
import com.socool.sinofaith.jsonparse.HttpJsonAdapter;
import com.socool.sinofaith.model.NoticeBean;
import com.socool.sinofaith.model.NoticeBean.Notice;
import com.socool.sinofaith.ui.NoticeActivity;
import com.socool.sinofaith.util.ConstansJsonUrl;
import com.socool.sinofaith.util.SinofaithUtil;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;

public class PushMessageService extends Service {
	public static final String ACTION = "com.ryantang.service.PollingService";
	private Notification mNotification;
	private NotificationManager mManager;
	private Notice mNotice;
	private String userMobile;

	@Override
	public void onCreate() {
		initNotifiManager();
		
	}

	@Override
	public void onStart(Intent intent, int startId) {
		getMessage();
	}

	// 初始化通知栏配置
	private void initNotifiManager() {
		mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		int icon = R.drawable.ic_launcher;
		mNotification = new Notification();
		mNotification.icon = icon;
		mNotification.tickerText = "新诤信最新通知";
		mNotification.defaults |= Notification.DEFAULT_SOUND;
		mNotification.flags = Notification.FLAG_AUTO_CANCEL;
	}

	// 弹出Notification
	@SuppressWarnings("deprecation")
	private void showNotification() {
		mNotification.when = System.currentTimeMillis();
		// Navigator to the new activity when click the notification title
		Intent i = new Intent(this, NoticeActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, i,
				Intent.FLAG_ACTIVITY_NEW_TASK);
		mNotification.setLatestEventInfo(this,
				mNotice.getTitle(),
				mNotice.getMessageContent(), pendingIntent);
		mManager.notify(0, mNotification);
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void getMessage() {

		FinalHttp fh = new FinalHttp();
		AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.getAppPush);
		params.put("did", SinofaithUtil.did);
		final SharedPreferences mySharedPreferences = getSharedPreferences(
				"push", Activity.MODE_PRIVATE);
		final String pushId = mySharedPreferences.getString("pushId", "");
		if(null==pushId || "".equals(pushId)){
			params.put("pid", "0");
		}else{
			params.put("pid", pushId);
		}
		params.put("Mobile",getSPString());

		fh.get(ConstansJsonUrl.REQUEST_URL, params, new AjaxCallBack() {
			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				super.onLoading(count, current);
			}

			@Override
			public void onSuccess(Object t) {
				// TODO Auto-generated method stub
				super.onSuccess(t);
				try {
					NoticeBean baseNoticeBean = HttpJsonAdapter.getInstance()
							.get(t.toString(), NoticeBean.class);
					if (baseNoticeBean.getResult().equals("0")) {
						ArrayList<Notice> noticeList = baseNoticeBean
								.getAppPushList();
						if (noticeList != null && noticeList.size() > 0) {
							mNotice = noticeList.get(0);

							if (!pushId.equals(mNotice.getPush_Id())) {
								showNotification();
							}
							// 实例化SharedPreferences.Editor对象（第二步）
							SharedPreferences.Editor editor = mySharedPreferences
									.edit();
							// 用putString的方法保存数据
							editor.putString("pushId", mNotice.getPush_Id());
							// 提交当前数据
							editor.commit();
						}
					}
				} catch (Exception e) {
				}
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				// TODO Auto-generated method stub
				super.onFailure(t, errorNo, strMsg);
			}

		});
	}
	
	private String getSPString(){
		SharedPreferences sp=this.getSharedPreferences("login", Context.MODE_PRIVATE);
		return sp.getString("UserMobile", "");
	}

}
